package com.tjbklx1.rocketMQTest.demo01;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import com.tjbklx1.rocketMQTest.constant.Host;

import java.util.UUID;

public class ProducerTest {
	private static DefaultMQProducer producer = null;

	public static void main(String[] args) {
		System.out.print("[----------]Start\n");
		int pro_count = 100;
//		if (args.length > 0) {
//			pro_count = Integer.parseInt(args[0]);
//		}
		try {
			producerStart();
			for (int i = 0; i < pro_count; i++) {
				String msg = "hello rocketmq " + i + "----" + UUID.randomUUID().toString();
				sendMessage(Host.TOPIC, msg);
				System.out.print(msg + "\n");
			}
		} finally {
			producer.shutdown();
		}
		System.out.print("[----------]Succeed\n");
	}

	private static boolean producerStart() {
		producer = new DefaultMQProducer(Host.PRODUCER_GROUP);
		producer.setNamesrvAddr(Host.HOST);
		producer.setInstanceName(UUID.randomUUID().toString());
		try {
			producer.start();
		} catch (MQClientException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private static boolean sendMessage(String topic, String str) {
		Message msg = new Message(topic, str.getBytes());
		try {
			producer.send(msg);
		} catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}